const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
//获取页面
const getEntry = function (globPath, pathDir) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;
    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);              //获取指定路径的文件夹的路径
        extname = path.extname(entry);              //返回指定路径的后缀名
        basename = path.basename(entry, extname);   //返回指定路径中的最后一部分(不包含后缀)
        pathname = path.join(dirname, basename);
        pathname = pathDir ? pathname.replace(path.normalize(pathDir), '') : pathname;
        entries[pathname] = './' + entry;
    }
    return entries;
}
const enterFile={vendors:[]};
//公共js
const jsPath=glob.sync('./src/js/**/*.js');
jsPath.forEach(function (files) {
    enterFile.vendors.push(files);
})
//公共css
const cssPath=glob.sync('./src/css/**/*.{css,less}');
cssPath.forEach(function (files) {
    enterFile.vendors.push(files);
})
//project
enterFile.projectDll = glob.sync('./src/main.js');
//page下资源
const pagePath=glob.sync('./src/pages/*');
pagePath.forEach(function (files) {
    let arr=[];
    arr.push(path.resolve(__dirname,glob.sync(files+'/**/index.js').toString()));
    arr.push(path.resolve(__dirname,glob.sync(files+'/**/index.{css,less}').toString()));
    enterFile[path.basename(files)]= arr;
})

const config={
    entry: enterFile,//类似于每个文件就是一个入口（不用向vue那样import了)
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'pages/[name]/index.js',
    },
    devtool: 'none',
    devServer: {
        contentBase: path.join(__dirname, "src"),
        compress: false,
        clientLogLevel:'none',
        quiet : true,
        port: 9001,
        hot: true
    },
    module: {
      rules: [{
        test: /\.js$/,
        exclude: /node_modules/,
        use:{
          loader: 'babel-loader',
          //options:{}//.babelrc  里面的内容会被注入到这里
        }
      },{
        test: /\.css|less$/,
        exclude: /node_modules/,
        use:[
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '/',
            }
          },
          // {loader: "style-loader"},MiniCssExtractPlugin和其冲突
          {loader: 'css-loader'},
          {loader: 'less-loader'}
        ]
      },{
        test: /\.(png|jpg|gif|svg|jpeg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              context:'src/',
              useRelativePath:true,
              name(filePath){
                //filePath = filePath.replace('@','src');
                if((/\\src\\pages\\/g).test(filePath)){
                  return '/[path][name].[ext]';
                }
                return '/images/[name].[ext]';
              }
            }
          }
        ]
      },{
        test: /\.(html)$/,
        use: [
          {
            loader: 'html-loader',
          }
        ]
      }]
    },
    plugins:[
      new MiniCssExtractPlugin({
        filename:`pages/[name]/index.css`
      })
    ],
    resolve:{
      extensions: ['*', '.js'],
      alias: {
        "@": path.resolve(__dirname,'src')
      }
    }
};

//页面文件打包
var pages = getEntry('src/**/index.html', 'src/');
for (var pathname in pages){
    //路径转化
    var pName = pathname.replace(/\\/g, '/');
    var conf = {
        filename: pName + '.html',      //生成的html存放路径，相对于 path
        template: './src/'+pName+'.html',
        minify:{
            romoveComments:true,        //移除HTML中的注释
            //collapseWhitespace:false    //删除空白符与换行符
        },
        inject: false//不插入js
    };
    if (pName.indexOf('pages') == -1) {
        conf.chunks = ['vendors','projectDll'];
        conf.inject= true;
        config.plugins.push(new HtmlWebpackPlugin(conf));
    }else {
        config.plugins.push(new HtmlWebpackPlugin(conf));
    }
}

module.exports = function(env,argv){
  if(env=='development'){
    config.devtool = 'source-map';//增强调试;
  }
  return config;
};
